from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QPointF
from PyQt5.QtGui import QPainter, QPen, QColor, QPolygonF, QFont
from PyQt5.QtWidgets import QWidget

from structures.basic_structure import BasicStructure
from trajectories.traj_base import BaseTrajectory
from view.layers.base_canvas_layer import BaseLayer


class CoordinateLayer(BaseLayer):

    LAYER_NAME = "Coordinate"
    """
    绘制坐标系
    """

    def __init__(self, ls: BasicStructure):
        super(CoordinateLayer, self).__init__(ls)

    def render(self, qp: QPainter, widget: QWidget):
        qp.setPen(QPen(QColor(0, 0, 0, alpha=120), 1, QtCore.Qt.PenStyle.SolidLine))

        canvas_width = widget.width()
        canvas_height = widget.height()

        # x轴
        qp.drawLine(QPointF(- canvas_width, 0), QPointF(canvas_width, 0))
        # y轴
        qp.drawLine(QPointF(0, - canvas_height), QPointF(0, canvas_height))

        # draw slice
        qp.setPen(QPen(QColor(0, 0, 0, alpha=150), 1, QtCore.Qt.PenStyle.SolidLine))
        font = qp.font()
        qp.setFont(QtGui.QFont('Arial', 6))

        ratio = self._ls._ratio
        max_x = widget.width() / 2.0
        max_y = widget.height() / 2.0 + self._ls.forward_ratio(30)
        # x轴标记 (每10mm一个)
        for x in range(0, canvas_width, int(10 * ratio)):
            if x >= max_x:
                break
            # 正（朝右）
            qp.drawLine(QPointF(x, 0), QPointF(x, 5))
            qp.drawText(QPointF(x - 5, -10), str(int(x / ratio)))
            # 负（朝左）
            qp.drawLine(QPointF(-x, 0), QPointF(-x, 5))
            qp.drawText(QPointF(-(x - 5), -10), str(int(-x / ratio)))

        # x arrow
        qp.drawLine(QPointF(max_x, 0), QPointF(max_x - 15, -5))
        qp.drawLine(QPointF(max_x, 0), QPointF(max_x - 15, +5))

        # y轴标记
        for y in range(0, canvas_height, int(10 * ratio)):
            if y >= max_y:
                break
            # 正（朝下）
            qp.drawLine(QPointF(0, y), QPointF(5, y))
            qp.drawText(QPointF(-18, y + 3), str(int(y / ratio)))
            # 负（朝上）
            qp.drawLine(QPointF(0, -y), QPointF(5, -y))
            qp.drawText(QPointF(-18, -(y + 3)), str(int(-y / ratio)))

        # y arrow
        qp.drawLine(QPointF(0, max_y), QPointF(-5, max_y - 15))
        qp.drawLine(QPointF(0, max_y), QPointF(+5, max_y - 15))

        qp.setFont(QtGui.QFont('Arial', 12))

        qp.drawText(QPointF(max_x - 30, -30), 'X')
        qp.drawText(QPointF(-40, max_y - 10), 'Y')

        qp.setFont(font)


